package com.novel.resource.cos.impl;

import com.novel.common.resource.IResourceService;
import com.novel.resource.cos.config.CosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 资源存储服务实现类
 *
 * @author novel
 * @date 2020/1/2
 */
@AllArgsConstructor
public class CosResourceServiceImpl implements IResourceService {
    /**
     * oss 操作客户端
     */
    private COSClient cosClient;
    /**
     * cos 配置
     */
    private CosConfig cosConfig;

    /**
     * 文件访问连接最大超时时间
     */
    private int fileCacheMaxTime;

    @Override
    public String getFileUrl(String sourceUrl) throws IOException {
        return cosClient.generatePresignedUrl(cosConfig.getBucketName(), sourceUrl, new Date(System.currentTimeMillis() + (1000 * 60 * fileCacheMaxTime))).toString();
    }

    @Override
    public boolean upLoadFile(String sourceUrl, String destPath) throws IOException {
        cosClient.putObject(cosConfig.getBucketName(), destPath, new File(sourceUrl));
        return true;
    }

    @Override
    public boolean upLoadFile(InputStream source, String destPath) throws IOException {
        ObjectMetadata metadata = new ObjectMetadata();
        // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
        metadata.setContentLength(Integer.valueOf(source.available()).longValue());
        // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
//        metadata.setContentType("image/jpeg");
        cosClient.putObject(cosConfig.getBucketName(), destPath, source, metadata);
        return true;
    }

    @Override
    public void download(String filePath, String localPath) throws IOException {
        cosClient.getObject(new GetObjectRequest(cosConfig.getBucketName(), filePath), new File(localPath));
    }

    @Override
    public boolean delete(String filePath) throws IOException {
        // 删除文件。
        cosClient.deleteObject(cosConfig.getBucketName(), filePath);
        return true;
    }

    @Override
    public byte[] readBytes(String filePath) throws IOException {
        try (InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), filePath).getObjectContent()) {
            return IOUtils.toByteArray(inputStream);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }
}
